package com.black.knight.chess;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.TextView;

import com.black.knight.chess.adapters.SPDestroyedFiguresAdapter;
import com.black.knight.chess.adapters.SPTableAdapter;
import com.black.knight.chess.domain.DeviceItem;
import com.black.knight.chess.domain.Move;
import com.black.knight.chess.domain.PNGProblem.PNGProblems;
import com.black.knight.chess.model.SPModel;
import com.black.knight.chess.model.SahModel;
import com.black.knight.chess.model.SettingsModel;
import com.black.knight.chess.utils.Utils;

public class StartPositionActivity extends Activity{

	private StartPositionActivity context;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        
    	this.context = this;
    	
    	requestWindowFeature(Window.FEATURE_NO_TITLE);
    	
    	Utils.setLanguage(SettingsModel.getInstance().getLanguage(), context);
    	
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        
        setContentView(R.layout.startposition_vertical);
        
        refresh(getResources().getConfiguration());
    }
    
    private void refresh(Configuration config) {             	
    	if(config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
    		setContentView(R.layout.startposition_horizontal);
    	} else {
    		setContentView(R.layout.startposition_vertical);
    	}
   	    GridView gridview = (GridView) findViewById(R.id.gridview);
        gridview.setSelector(R.drawable.empty);
        gridview.setAdapter(new SPTableAdapter(this));
        gridview.setAddStatesFromChildren(true);
        gridview.setFastScrollEnabled(true);
        gridview.setClipChildren(true);
        gridview.setBackgroundResource(R.drawable.background);
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
				if(SPModel.getInstance().getSelectedFigure() != null) {				
					
					if(Move.isWhiteKing(SPModel.getInstance().getSelectedFigure())) {
						int row = position / 8;
						int column = position % 8;
						
						if(Move.isBlackKing(SPModel.getInstance().getFigure(row-1, column)) ||
						   Move.isBlackKing(SPModel.getInstance().getFigure(row+1, column)) ||
						   Move.isBlackKing(SPModel.getInstance().getFigure(row, column-1)) ||
						   Move.isBlackKing(SPModel.getInstance().getFigure(row, column+1)) ||
						   Move.isBlackKing(SPModel.getInstance().getFigure(row+1, column+1)) ||
						   Move.isBlackKing(SPModel.getInstance().getFigure(row+1, column-1)) ||
						   Move.isBlackKing(SPModel.getInstance().getFigure(row-1, column-1)) ||
						   Move.isBlackKing(SPModel.getInstance().getFigure(row-1, column+1))
						) return;
					} else if(Move.isBlackKing(SPModel.getInstance().getSelectedFigure())) {
						int row = position / 8;
						int column = position % 8;
						
						if(Move.isWhiteKing(SPModel.getInstance().getFigure(row-1, column)) ||
						   Move.isWhiteKing(SPModel.getInstance().getFigure(row+1, column)) ||
						   Move.isWhiteKing(SPModel.getInstance().getFigure(row, column-1)) ||
						   Move.isWhiteKing(SPModel.getInstance().getFigure(row, column+1)) ||
						   Move.isWhiteKing(SPModel.getInstance().getFigure(row+1, column+1)) ||
						   Move.isWhiteKing(SPModel.getInstance().getFigure(row+1, column-1)) ||
						   Move.isWhiteKing(SPModel.getInstance().getFigure(row-1, column-1)) ||
						   Move.isWhiteKing(SPModel.getInstance().getFigure(row-1, column+1))
						) return;
					}
					
					if((SPModel.getInstance().getSelectedFigure() == R.drawable.bp || SPModel.getInstance().getSelectedFigure() == R.drawable.wp) && (position > 55 || position < 8)) return;
					
					if(SPModel.getInstance().getFields()[position] == R.drawable.bk || SPModel.getInstance().getFields()[position] == R.drawable.wk) return;
					
					if(SPModel.getInstance().getFields()[position] != R.drawable.empty) {
						SPModel.getInstance().destroyFigure(SPModel.getInstance().getFields()[position], Move.isFigureWhite(SPModel.getInstance().getFields()[position]));
					}
					
					if(SPModel.getInstance().getSelectedFigure() == SPModel.getInstance().getFields()[position]) {
						SPModel.getInstance().getFields()[position] = R.drawable.empty;
						
						SPModel.getInstance().setSelectedFlagTable(-1);
						SPModel.getInstance().setSelectedFigure(null);
						refreshAll();
						
						return;
					}
					
					SPModel.getInstance().getFields()[position] = SPModel.getInstance().getSelectedFigure();
					
					if(SPModel.getInstance().getSelectedFlagBlack() != -1) {
						SPModel.getInstance().getDestroyedFiguresBlack()[SPModel.getInstance().getSelectedFlagBlack()] = R.drawable.empty;
					} else if(SPModel.getInstance().getSelectedFlagWhite() != -1) {
						SPModel.getInstance().getDestroyedFiguresWhite()[SPModel.getInstance().getSelectedFlagWhite()] = R.drawable.empty;
					} else if(SPModel.getInstance().getSelectedFlagTable() != -1) {
						SPModel.getInstance().getFields()[SPModel.getInstance().getSelectedFlagTable()] = R.drawable.empty;
					}
					
					SPModel.getInstance().setSelectedFlagTable(-1);
					SPModel.getInstance().setSelectedFigure(null);
				} else if(SPModel.getInstance().getFields()[position] != R.drawable.empty) {
					SPModel.getInstance().setSelectedFlagTable(position);
				} else {
					SPModel.getInstance().setSelectedFigure(null);
					SPModel.getInstance().setSelectedFlagTable(-1);
				}
				
				refreshAll();
			}
		});
        
        // Initialize destroyed layouts
        GridView destroyedWhiteFigures = (GridView) findViewById(R.id.destroyedWhiteFigures);
        destroyedWhiteFigures.setAdapter(new SPDestroyedFiguresAdapter(this, true));
        destroyedWhiteFigures.setVerticalScrollBarEnabled(false);
        destroyedWhiteFigures.setSelector(R.drawable.empty); 
        destroyedWhiteFigures.setFastScrollEnabled(true);
        destroyedWhiteFigures.setClipChildren(true);
        destroyedWhiteFigures.setAddStatesFromChildren(true);
        destroyedWhiteFigures.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
				if(SPModel.getInstance().getDestroyedFiguresWhite()[position] != R.drawable.empty) {
					SPModel.getInstance().setSelectedFlagWhite(position);
				}
				
				refreshAll();
			}
		});
        
        GridView destroyedBlackFigures = (GridView) findViewById(R.id.destroyedBlackFigures);
        destroyedBlackFigures.setAdapter(new SPDestroyedFiguresAdapter(this, false));
        destroyedBlackFigures.setVerticalScrollBarEnabled(false);
        destroyedBlackFigures.setSelector(R.drawable.empty);
        destroyedBlackFigures.setFastScrollEnabled(true);
        destroyedBlackFigures.setClipChildren(true);
        destroyedBlackFigures.setAddStatesFromChildren(true);
        destroyedBlackFigures.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
				if(SPModel.getInstance().getDestroyedFiguresBlack()[position] != R.drawable.empty) {
					SPModel.getInstance().setSelectedFlagBlack(position);
				}
				
				refreshAll();
			}
		});
        
        LinearLayout gridlayout = (LinearLayout) findViewById(R.id.gridlayout);
        
        gridview.setLayoutParams(new LinearLayout.LayoutParams(SahModel.getTableWidth(), SahModel.getTableWidth()));
        if(Utils.getOrientation() == 1) {
       	 	gridlayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, SahModel.getTableWidth()));
        }
	}
    
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        Utils.setLanguage(SettingsModel.getInstance().getLanguage(), context);
    	refresh(newConfig);
      
    	super.onConfigurationChanged(newConfig);
    }
	
	private void refreshAll() {
		GridView gridview = (GridView) findViewById(R.id.gridview);
		SPTableAdapter adapter = (SPTableAdapter)gridview.getAdapter();
		adapter.notifyDataSetChanged();
		
		GridView destroyedWhite = (GridView) findViewById(R.id.destroyedWhiteFigures);
		SPDestroyedFiguresAdapter adapterWhite = (SPDestroyedFiguresAdapter)destroyedWhite.getAdapter();
		adapterWhite.notifyDataSetChanged();	
		
		GridView destroyedBlack = (GridView) findViewById(R.id.destroyedBlackFigures);
		SPDestroyedFiguresAdapter adapterBlack = (SPDestroyedFiguresAdapter)destroyedBlack.getAdapter();
		adapterBlack.notifyDataSetChanged();	
	}
	
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	
    	switch (item.getItemId()) {
        	case R.id.playgame:
	        	final ArrayList<DeviceItem> gameOptions = new ArrayList<DeviceItem>();
	        	
	        	gameOptions.add(new DeviceItem(getResources().getString(R.string.white), R.drawable.wn));
	        	gameOptions.add(new DeviceItem(getResources().getString(R.string.black), R.drawable.bn));

	    		ListAdapter adapter = new ArrayAdapter<DeviceItem>(this, android.R.layout.select_dialog_item, android.R.id.text1, gameOptions){
	    	        public View getView(int position, View convertView, ViewGroup parent) {
	    	            View v = super.getView(position, convertView, parent);
	    	            TextView tv = (TextView)v.findViewById(android.R.id.text1);

	    	            tv.setCompoundDrawablesWithIntrinsicBounds(gameOptions.get(position).icon, 0, 0, 0);
	    	            tv.setTextSize(18);

	    	            int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
	    	            tv.setCompoundDrawablePadding(dp5);

	    	            return v;
	    	        }
	    		};

	        	AlertDialog.Builder builder = new AlertDialog.Builder(this);
	        	builder.setTitle(getResources().getString(R.string.who_play_first));
	        	builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
	        	    public void onClick(DialogInterface dialog, int item) {
	        	    	if(item == 0) {
	        	    		SPModel.getInstance().setWhitePlayFirst(true);
	        	    	} else if(item == 1) {
	        	    		SPModel.getInstance().setWhitePlayFirst(false);
	        	    	}
	        	    	
	        	    	context.finish();
	        	    	
	        	    	Utils.chooseNewGameType(SahModel.context, SPModel.getInstance().getFEN(), "White", "Black", false);
	        	    }
	        	});
	        	AlertDialog alert = builder.create();
	        	alert.show();
	            return true;
	        case R.id.saveproblem:
	        	saveProblemAs(this);
	        	
	        	return true;
	        default:
	            return super.onOptionsItemSelected(item);
        }
    }
    
    private static void saveProblemAs(final Context context) {    	
    	LinearLayout layout = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.mate_in_moves, null, false);
    	
    	final EditText mateInField = (EditText)layout.findViewById(R.id.mateInField);
    	final EditText problemNameField = (EditText)layout.findViewById(R.id.problemNameField);
    	
    	AlertDialog.Builder builder = new AlertDialog.Builder(context);
    	builder.setView(layout)
    		   .setTitle(context.getResources().getString(R.string.save_as_problem))
    	       .setNegativeButton(context.getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	           }
    	       })
    		   .setPositiveButton(context.getResources().getString(R.string.save), new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	        	   if(mateInField.getText().length() == 0) {
    	        		   Utils.displayAlertMessage(context, context.getResources().getString(R.string.enter_all_fields));
    	        		   
    	        		   return;
    	        	   }
    	        	   
    	        	   int mateIn = Integer.valueOf(mateInField.getText().toString());
   					   
    	        	   if(problemNameField.getText().toString().length() == 0) {
    	        		   Utils.displayAlertMessage(context, context.getResources().getString(R.string.enter_all_fields));
    	        		   
    	        		   return;
    	        	   }
    	        	   
	   				   if(mateIn > 0) {
	   					   final ContentValues values = new ContentValues();
	   					   values.put(PNGProblems.DESCRIPTION, problemNameField.getText().toString());
	   					   values.put(PNGProblems.FEN, SPModel.getInstance().getFEN());
	   					   values.put(PNGProblems.MATE_IN, mateIn);
	   					   
	   					   SahModel.context.getContentResolver().insert(PNGProblems.CONTENT_URI, values);
	   				   } else {
	   					   Utils.displayAlertMessage(context, context.getResources().getString(R.string.moves_field_must_be_greater_than_zero));
	   				   }
    	           }
    	       });
    	builder.create().show(); 	
    }
    
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.startposition_menu, menu);
        return true;
    }
}